﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Forms;
using OfficeOpenXml;

namespace ServerAnalysisReport
{
    public static class GenerateExcel
    {
        //Chek the File exists or not
        //Delete file if exists 
        //If failed to delete, re-try do-while loop to set new file name
        //I havent decided to use RANDOM number or increamental counter or keep it with loop as yet.
        //OR ultimately, can bring up filesave dialogue... 
        //Problem is that GenerateExcel.cs is called as callback, and potentially stop the thread from processing.

        private static FileInfo CreateNewFile(string servername)
        {
            DateTime dt;
            bool fileCreation = false;
            FileInfo newFile;
            do
            {
                dt = DateTime.Now;
                 newFile = new FileInfo(servername + "-" + dt.Year + dt.Month + dt.Day + "-" + dt.Hour + dt.Minute + dt.Second +
                                 ".xlsx");
                if (newFile.Exists)
                {
                    try
                    {
                        newFile.Delete();
                        fileCreation = true;
                    }
                    catch (Exception ex)
                    {
#if DEBUG
                        Debug.WriteLine("FileAccess Error " + ex.ToString());
#endif
                        fileCreation = false;
                    }
                }
            } while (fileCreation);
            return newFile;
        }

        public static void createExcelReport(ArrayList totalServerStats)
        {
            
            string servername = totalServerStats[0].ToString();
            totalServerStats.RemoveAt(0);//remove embedded target servername

            FileInfo newFile = CreateNewFile(servername);


            ExcelPackage xlPackage = new ExcelPackage(newFile);

            #if DEBUG
            Debug.WriteLine("Total Server Stats Count "+totalServerStats.Count);
            #endif
            foreach (ArrayList SingleMetricStats in totalServerStats)
            {
                #if DEBUG
                Debug.WriteLine("SingleServer Stats Count "+SingleMetricStats.Count);
                Debug.WriteLine("SingleServer Stats Metric " + SingleMetricStats[0]);
                #endif

                ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets.Add(SingleMetricStats[0].ToString());

                switch (Convert.ToInt16(SingleMetricStats[0]))
                {
                    case 5:
                        worksheet.Name = SingleMetricStats[0] + " Pages Per Sec";
                        break;
                    case 7:
                        worksheet.Name = SingleMetricStats[0] + " Context Switches";
                        break;
                    case 8:
                        worksheet.Name = SingleMetricStats[0] + " Inactive Sessions";
                        break;
                    case 9:
                        worksheet.Name = SingleMetricStats[0] + " Active Sessions";
                        break;
                    case 10:
                        worksheet.Name = SingleMetricStats[0] + " % Processor Time";
                        break;

                    default:
                        worksheet.Name = "No Metric specified ";
                        break;
                }                

                worksheet.Cell(1, 1).Value = "Server Name";
                worksheet.Cell(1, 2).Value = servername;
                worksheet.Cell(2, 1).Value = "Date GMT0";
                worksheet.Cell(2, 2).Value = "GMT BIASTIME";
                worksheet.Cell(2, 3).Value = "METRIC DURATION (SEC)";
                worksheet.Cell(2, 4).Value = "MIN";
                worksheet.Cell(2, 5).Value = "MAX";
                worksheet.Cell(2, 6).Value = "MEAN";
                worksheet.Cell(2, 7).Value = "STD DEV";
                SingleMetricStats.RemoveRange(0,2);//remove embedded metric id code.
                int rowcounter = 3;
                foreach (string[] stats in SingleMetricStats)
                {

                    if (stats == null)
                    {
                        break;
                    }
                    for (int counter = 0; counter < stats.Length;counter++ )
                    {
                        try
                        {
                            if (stats[counter] == null)
                            {
                                break;
                            }
                            worksheet.Cell(rowcounter, counter+1).Value = stats[counter];
                        }
                        catch (Exception exx)
                        {
                            MessageBox.Show("stat" + stats[0] + " " + stats[1] + " " + stats[3] + " " + stats[4] + " " + stats[5] + " " + stats[6]);
                            MessageBox.Show("error " + exx);
                        }

                    }
                    rowcounter++;
                }
                xlPackage.Save();
                
                //counter++;
            }//end foreach ArrayList SingleMetricstats

            xlPackage.Dispose(); //close file access to Excel 2007 file , other app will not be able to open if file access is not closed.
        }//end void createReport

        
    }
}
